//
//  M4ProductDetailViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/19.
//

import UIKit
import KakaJSON
import ActiveLabel

class M4ProductDetailViewController: M4BaseViewController {
    
    @IBOutlet weak var M4PDBottomFirstView: UIView!
    
//    @IBOutlet weak var M4PDFirstViewHeight: NSLayoutConstraint!
    @IBOutlet weak var M4PDFirstImageView: UIImageView!
    
    @IBOutlet weak var M4PDFirstLabel1: ActiveLabel!

    @IBOutlet weak var M4PDFirstLabel2: UILabel!
    
    @IBOutlet weak var M4PDFirstLabel2Top: NSLayoutConstraint!
    
    @IBOutlet weak var M4PDCloseButton: UIButton!
    
    @IBOutlet weak var M4PDBottomSecondView: UIView!
    
    @IBOutlet weak var M4PDCountDownLabel: UILabel!
    
    @IBOutlet weak var M4PDjinbiImage: UIImageView!
    
    @IBOutlet weak var M4PDAbandonButton: UIButton!
    
    @IBOutlet weak var M4PDCountDownBottom: NSLayoutConstraint!
    
    @IBOutlet weak var M4PDApplyButton: UIButton!
    
    private var m4enterTime: Int = 0
    
    private var m4check: Bool = true
    
    private var detailData: M4ProductDetailModel?
    
    private var selectEDU: M4UserProductList?
    
    private var M4ProTimer: Timer?
    
    private var M4ProRemainTime: Int = 0
    
    private var M4selectBank: M4BankListModel?
    
    private var M4isAgreeCreditChangeDefault: Int = 0
    
    private var M4isAuto: Bool = false
    
    private var loading: M4LoadingAlertView = M4LoadingAlertView()
    
    lazy var m4shouxinAlert: M4SShouxinAlertView = {
        let alert = UINib(nibName: "M4SShouxinAlertView", bundle: nil).instantiate(withOwner: self).last as! M4SShouxinAlertView
        alert.m4useBlock = {
            self.M4isAgreeCreditChangeDefault = 1
            if self.M4isAuto {
                self.loading.M4LoadingAlertShow()
                self.M4ProTimeTaskNet(status: 1, type: 2)
            }
            else {
                self.M4AgreeCreditChange()
            }
        }
        alert.m4cancelBlock = {
            self.M4isAgreeCreditChangeDefault = 0
            if self.M4isAuto {
                self.loading.M4LoadingAlertShow()
                self.M4ProTimeTaskNet(status: 1, type: 2)
            }
            else {
                self.M4AgreeCreditChange()
            }
        }
        return alert
    }()
    
    lazy var m4closeTimerAlert: M4CloseTimerAlertView = {
        let alert = UINib(nibName: "M4CloseTimerAlertView", bundle: nil).instantiate(withOwner: self).last as! M4CloseTimerAlertView
        alert.action2Block = {
            self.loading.M4LoadingAlertShow()
            self.M4ProTimeTaskNet(status: 0, type: 1)
        }
        return alert
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        M4NavBarColor = COLOR_00479D
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        m4enterTime = Int(Date().timeIntervalSince1970 * 1000)
        M4NavTitle(M4Title: "Confirmar cuota", M4NavTitleColor: .white)
        let bgView = UIView()
        bgView.backgroundColor = COLOR_00479D
        view.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(M4NavigationFullHeight()-0.5)
            make.height.equalTo(40)
        }
        M4PDBottomFirstView.layer.cornerRadius = 5
        M4PDBottomFirstView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        M4PDBottomSecondView.layer.cornerRadius = 5
        M4PDBottomSecondView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        M4PDCloseButton.M4ButtonUnderline()
        M4PDAbandonButton.M4ButtonUnderline()
        view.addSubview(M4TableView)
        M4TableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(M4NavigationFullHeight())
            make.bottom.equalTo(M4PDBottomFirstView.snp.top)
        }
        M4addRefreshToTaleView {
            self.M4ProductDetailNet()
        }
        M4ProductDetailNet()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        M4DeviceDataManager.m4DeviceShare.m4RqI = (Int(Date().timeIntervalSince1970 * 1000) - m4enterTime)
    }
    
    override func M4BackClick(sender: UIButton) {
        let audit = M4UserDataManager.m4UserShare.M4AuditAccount
        if detailData?.Bjfad == 1 && audit == 0 && M4isAuto {
            if self.navigationController?.viewControllers.first is M4CrediteInfoViewController {
                AppDelegate.keyWindow()?.rootViewController = M4TabBarViewController()
            }
            else {
                //self.navigationController?.popToRootViewController(animated: true)
                //需要挽留弹框
                M4InfosPageBack()
            }
        }
        else {
            M4InfosPageBack()
        }
        sender.M4EventUnavailable = false
        
        self.uploadData()
    }
    
    override func M4CellAction(_ action: M4IDAction) {
        let type = M4ProDetailStatusAction(rawValue: action.M4ActionType)
        if type == .M4DetailBankAction {
            let page = M4UserBankViewController()
            page.fromDetail = true
            page.M4SelectBankBlock = { selectBank in
                self.M4selectBank = selectBank
                self.detailData?.PeTqTNV?.YZaWhPDiAj = selectBank?.IJvjMwzORFx
                if self.M4isAuto {
                    self.loading.M4LoadingAlertShow()
                    self.M4ProTimeTaskNet(status: 1, type: 3)
                }
                else {
                    self.M4ChangeBankInfo()
                }
            }
            self.navigationController?.pushViewController(page, animated: true)
        }
        else if type == .M4DetailAmountAction {
            var amounts: [M4InfoItemListModel] = []
            for i in 0..<(detailData?.GxGcD?.count ?? 0) {
                var model = M4InfoItemListModel()
                let amountStr = "$ \(M4String.M4BlankAmount(original: "\(detailData?.GxGcD?[i].GZetioHF ?? 0)"))"
                model.GTG = amountStr
                model.IfSps = "\(i)"
                amounts.append(model)
            }
            let listView = UINib(nibName: "M4InfosListAlertView", bundle: nil).instantiate(withOwner: self).last as! M4InfosListAlertView
            
            listView.M4InfosListUpdateUI(title: " ", data: amounts)
            listView.M4AmountReturn = { choose in
                let index = Int(choose.IfSps ?? "0") ?? 0
                self.selectEDU = self.detailData?.GxGcD?[index]
                self.M4PDApplyButton.setTitle("Solicitar ahora $\(M4String.M4BlankAmount(original: "\(self.selectEDU?.GZetioHF ?? 0)"))", for: .normal)
                self.M4DetailDataSource()
            }
            if selectEDU != nil {
                for k in 0..<listView.M4CellData.count {
                    let str = listView.M4CellData[k].GTG
                    let select = "$ \(M4String.M4BlankAmount(original: "\(selectEDU?.GZetioHF ?? 0)"))"
                    if str == select {
                        listView.M4SelectedIndex = k
                        break
                    }
                }
            }
            listView.M4PopViewShow(subview: listView.M4InfosListBGView)
        }
        else if type == .M4DetailCheckAction {
            let isSelect = action.M4ActionData as? Bool ?? false
            self.m4check = isSelect
        }
        else if type == .M4DetailPrivacyAction {
            let str = action.M4ActionData as? String ?? ""
            let htmlVC = M4HtmlWebViewController()
            htmlVC.M4WebTitle = str
            htmlVC.M4WebUrl = M4NetworkAPI.m4htmlPath.rawValue + "/nafvsdahgv"
            htmlVC.M4OpenPrivacy = true
            self.navigationController?.pushViewController(htmlVC, animated: true)
        }
    }
    
    override func M4DataRefresh() {
        M4ProductDetailNet()
    }
    
    deinit {
        if M4ProTimer != nil {
            M4ProStopTimer()
        }
    }
    
    
    @IBAction func M4PDCloseClick(_ sender: UIButton) {//取消双授信
        m4shouxinAlert.M4AlertViewShow()
        sender.M4EventUnavailable = false
    }
    
    @IBAction func M4PDAbandonCLick(_ sender: UIButton) {//放弃自动借款
        m4closeTimerAlert.M4AlertViewShow()
        sender.M4EventUnavailable = false
        
        Afqwr = Int(Date().timeIntervalSince1970 * 1000)
    }
    
    @IBAction func M4PDApplyClick(_ sender: UIButton) {
        SDQWR = Int(Date().timeIntervalSince1970  * 1000)
        if m4check {
            let param: [String : Any] = ["HYZtxhSixE": "ESP", "EyZCtHwlA": M4UserDataManager.m4UserShare.M4Itemcode, "ZlMAM": M4UserDataManager.m4UserShare.M4ProductCode, "Umoz": M4UserDataManager.m4UserShare.M4Token, "LMxzok": detailData?.PeTqTNV?.YZaWhPDiAj ?? 0, "VZXJYPoyU": selectEDU?.WLfskwSn ?? 0, "xcziPPEIo": M4isAgreeCreditChangeDefault]
            if M4UserDataManager.m4UserShare.M4AuditAccount == 1 {
                let page = M4LoanPrivacyViewController()
                page.productPara = param
                page.productID = selectEDU?.WLfskwSn ?? 0
                self.navigationController?.pushViewController(page, animated: true)
                sender.M4EventUnavailable = false
            }
            else {
                M4LimitVerification().M4LimitDataAsk1 { arrayCount in
                    sender.M4EventUnavailable = false
                    if arrayCount.count > 0 {
                        M4LimitVerification().M4_showAskAlert(arr: arrayCount) { _ in }
                    }
                    else {
                        //检查/上传埋点，跳转提单页
                        M4PublicNetwork.M4CheckNeedUpload { t in
                            if t == 1 {
                                if M4UserDataManager.M4HasShowUploadPage == false {
                                    M4PublicNetwork.M4ShowUploadAlert { r in
                                        if r == true {
                                            self.M4UploadDataDone(r: r, param: param)
                                        }
                                    }
                                } else {
                                    M4PublicNetwork.M4ShowUploadAlert { r in
                                        if r == true {
                                            self.M4UploadDataDone(r: r, param: param)
                                        }
                                    }
                                }
                            } else {
                                self.M4UploadDataDone(r: true, param: param)
                            }
                        }
                        
                        
                        
//                        if M4UserDataManager.M4HasShowUploadPage == false {
//                            let uploadController = M4UploadController()
//                            uploadController.M4UploadResult = { issuccess in
//                                self.M4UploadDataDone(r: issuccess, param: param)
//                            }
//                            self.navigationController?.pushViewController(uploadController, animated: true)
//                        } else {
//                            let loading = M4LoadingAlertView()
//                            loading.M4LoadingAlertShow()
//                            M4PublicNetwork.M4VerficationPointDataNet(false) { issuccess in
//                                loading.M4AlertViewHidden()
//                                self.M4UploadDataDone(r: issuccess, param: param)
//                            }
//                        }
                    }
                }
            }
            print("Apply")
        }
        else {
            sender.M4EventUnavailable = false
            self.view.makeToast("Lea y acepte la divulgación de información", position: .center)
        }
    }
    
    func M4UploadDataDone(r: Bool, param: [String:Any]) {
        let loading = M4LoadingAlertView()
        loading.M4LoadingAlertShow()
        M4PublicNetwork.M4SubmitLoanNet(false, paramnet: param) { issuccess, loanId in
            loading.M4AlertViewHidden()
            if issuccess {
                self.Srqwe = 1
                M4DeviceDataManager.m4DeviceShare.m4QhnB = (Int(Date().timeIntervalSince1970) - M4DeviceDataManager.m4DeviceShare.m4firstEnterTime) * 1000
                let page = M4LoanResultViewController()
                page.M4LoanId = loanId
                page.M4PageFromLoan = true
                self.navigationController?.pushViewController(page, animated: true)
            } else {
                self.Srqwe = 0
            }
            self.uploadData()
        }
    }
    
    var SDQWR = 0
    var Afqwr = 0
    var Srqwe = 0
    var asdqwrA = 0
    func uploadData() {
        let params: [[String:Any]] = [
            [
                "adga" : 9001,
                "sdqw" : inTime,
                "hgjyj" : Int(Date().timeIntervalSince1970 * 1000) ,
                "SDQWR" : SDQWR,
                "Afqwr" : Afqwr,
                "Srqwe" : Srqwe,
                "asdqwrA" : asdqwrA,
                "fASDW" : selectEDU?.RExEuGxUWqg ?? "",
                "SFFF" : selectEDU?.GZetioHF ?? 0,
            ]
        ]
        M4HiddenPointDataManager.M4UploadHiddenPoint(type: .ConfimLoan, paramsKey: "DASdq", params: params, complete: nil)
    }
}

extension M4ProductDetailViewController {
    
    private func M4DetailDataSource() {
        M4TableSources.removeAll()
        M4TableSources.append(M4TableViewCellData("M4ProDetailFirstCell", XIB: true, selectEDU?.GZetioHF ?? 0, detailData?.PeTqTNV ?? M4UserLatestBankData(), detailData?.gkdfc ?? 0))
        M4TableSources.append(M4TableViewCellData("M4ProDetailSecondCell", XIB: true, selectEDU ?? M4UserProductList()))
        M4TableView.reloadData()
    }
    
    @objc private func M4ProTimeCountDown() {
        M4ProRemainTime -= 1
        if M4ProRemainTime <= 0 {
            M4ProStopTimer()
            if self.navigationController?.viewControllers.first is M4FirstInfoViewController {
                AppDelegate.keyWindow()?.rootViewController = M4TabBarViewController()
            }
            else {
                self.navigationController?.popToRootViewController(animated: true)
            }
        }
        else {
            let timeStr = M4String.M4TimeStampToString(timeStamp: M4ProRemainTime)
            let labelStr = "      Beneficio de tiempo limitado, se enviará la solicitud automáticamente después de \(timeStr), con tasa\ndeaprobación de 95%"
            let attr = NSMutableAttributedString(string: labelStr)
            if let range = labelStr.range(of: timeStr) {
                let nsRange = NSRange(range, in: labelStr)
                attr.addAttributes([.font: UIFont.systemFont(ofSize: 12, weight: .semibold), .foregroundColor: COLOR_FF1406], range: nsRange)
            }
            M4PDCountDownLabel.attributedText = attr
        }
    }
    
    private func M4ProStopTimer() {
        M4ProTimer?.invalidate()
        M4ProTimer = nil
        M4ProRemainTime = 0
    }
    
    private func M4TimerUI(time: Int) {
        if time > 0 {
            self.M4isAuto = true
            self.M4ProRemainTime = time / 1000
            let timeStr = M4String.M4TimeStampToString(timeStamp: M4ProRemainTime)
            let labelStr = "      Beneficio de tiempo limitado, se enviará la solicitud automáticamente después de \(timeStr), con tasa\ndeaprobación de 95%"
            let attr = NSMutableAttributedString(string: labelStr)
            if let range = labelStr.range(of: timeStr) {
                let nsRange = NSRange(range, in: labelStr)
                attr.addAttributes([.font: UIFont.systemFont(ofSize: 12, weight: .semibold), .foregroundColor: COLOR_FF1406], range: nsRange)
            }
            M4PDCountDownLabel.attributedText = attr
            if self.M4ProTimer == nil {
                self.M4ProTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.M4ProTimeCountDown), userInfo: nil, repeats: true)
                RunLoop.main.add(self.M4ProTimer!, forMode: .common)
            }
        }
        else {
            self.M4isAuto = false
            if self.M4ProTimer != nil {
                self.M4ProStopTimer()
            }
            self.M4PDCountDownLabel.text = ""
        }
        self.M4PDCountDownLabel.isHidden = time <= 0 ? true : false
        self.M4PDjinbiImage.isHidden = time <= 0 ? true : false
        self.M4PDAbandonButton.isHidden = time <= 0 ? true : false
        self.M4PDCountDownBottom.constant = time <= 0 ? 0 : 10
    }
    
    private func M4AgreeCreditChange() {
        if M4isAgreeCreditChangeDefault == 1 {
            self.M4PDFirstLabel1.text = "Privilegios de usuario Premium"
        }
        else {
            let customType = ActiveType.custom(pattern: "Haga clic para utilizar")
            M4PDFirstLabel1.enabledTypes = [customType]
            M4PDFirstLabel1.customize { label in
                label.text = "Sus privilegios aprobados de auditoría no se utilizan Haga clic para utilizar"
                
                label.handleCustomTap(for: customType) { element in
                    self.m4shouxinAlert.M4AlertViewShow()
                }
                
                label.configureLinkAttribute = { (type, attributes, isSelected) in
                    var atts = attributes
                    atts[.underlineStyle] = NSUnderlineStyle.single.rawValue
                    atts[.underlineColor] = UIColor.white
                    return atts
                }
                label.customColor[customType] = .white
                label.customSelectedColor[customType] = .white
            }
        }
        self.M4PDFirstLabel2.text = M4isAgreeCreditChangeDefault == 1 ? "Si no se aprueba la solicitud actual, se reevaluará y se le otorgará el préstamo exclusivo." : ""
        self.M4PDCloseButton.isHidden = M4isAgreeCreditChangeDefault == 1 ? false : true
    }
    
    private func M4ChangeBankInfo() {
        self.detailData?.PeTqTNV?.ODpK = M4selectBank?.QroFb
        self.detailData?.PeTqTNV?.HKcZzMeYYUi = M4selectBank?.MpLhEfItt
        self.detailData?.PeTqTNV?.GleVPMpEJlv = M4selectBank?.ILeRqUStnqr
        self.detailData?.PeTqTNV?.OCZXjUbp = M4selectBank?.RBeMwxjMj
        self.detailData?.PeTqTNV?.VHKIfeFGTG = M4selectBank?.WqJEStLi
        self.M4DetailDataSource()
    }
    
}

extension M4ProductDetailViewController {
    
    private func M4ProductDetailNet() {
        loading.M4LoadingAlertShow()
        let para: [String : Any] = ["WXlFy": "ESP", "MVKadTRdk": M4UserDataManager.m4UserShare.M4Itemcode, "AIgHy": M4UserDataManager.m4UserShare.M4ProductCode, "XIGHilT": M4UserDataManager.m4UserShare.M4Token]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4productDetail, .post, params: para), false) { model in
            self.M4endRefresh()
            self.M4isAuto = false
            if model.code == 1 {
                self.asdqwrA = 1
                let data = model.data as? [String : Any]
                self.detailData = data?.kj.model(M4ProductDetailModel.self)
                if self.detailData?.GxGcD?.count ?? 0 > 0 {
                    self.selectEDU = self.detailData?.GxGcD?[0]
                }
                self.M4PDApplyButton.setTitle("Solicitar ahora $\(M4String.M4BlankAmount(original: "\(self.selectEDU?.GZetioHF ?? 0)"))", for: .normal)
                self.M4DetailDataSource()
                let audit = M4UserDataManager.m4UserShare.M4AuditAccount
                if audit != 1 && self.detailData?.Bjfad == 1 {
                    if self.detailData?.yusdfx == -2 {
                        self.M4ProTimeTaskNet(status: 1)
                    }
                    else {
                        self.loading.M4AlertViewHidden()
                        let executionTime = self.detailData?.loh ?? 0
                        self.M4TimerUI(time: executionTime)
                    }
                }
                else {
                    self.loading.M4AlertViewHidden()
                    self.M4PDCountDownLabel.text = ""
                    self.M4PDCountDownLabel.isHidden = true
                    self.M4PDjinbiImage.isHidden = true
                    self.M4PDAbandonButton.isHidden = true
                    self.M4PDCountDownBottom.constant = 0
                }
                self.M4PDBottomFirstView.isHidden = audit == 1 || (self.detailData?.NJCs == 0 && audit == 0) ? true : false
                self.M4PDFirstImageView.isHidden = audit == 1 || (self.detailData?.NJCs == 0 && audit == 0) ? true : false
                if audit == 1 || (self.detailData?.NJCs == 0 && audit == 0) {
                    self.M4PDFirstLabel1.text = ""
                    self.M4PDFirstLabel2.text = ""
                    self.M4PDFirstLabel2Top.constant = 0
                    self.M4PDCloseButton.isHidden = true
                }
                else {
                    self.M4isAgreeCreditChangeDefault = self.detailData?.eUjdf ?? 0
                    self.M4AgreeCreditChange()
                }
                
            }
            else {
                self.asdqwrA = 0
                self.loading.M4AlertViewHidden()
                self.view.makeToast(model.message, position: .center)
            }
            
            if M4UserDataManager.m4UserShare.M4AuditAccount == 1 {
                self.M4PDBottomFirstView.isHidden = true
            }
        }
    }
    
    private func M4ProTimeTaskNet(status: Int, type: Int = 1) {
        let para: [String : Any] = ["oqwE": "ESP", "ojsadE": M4UserDataManager.m4UserShare.M4Itemcode, "qweQ": M4UserDataManager.m4UserShare.M4ProductCode, "asojdE": M4UserDataManager.m4UserShare.M4Token, "dwqdR": detailData?.PeTqTNV?.YZaWhPDiAj ?? 0, "wqexzcgE": selectEDU?.WLfskwSn ?? 0, "fdssE": status, "dsaRR": M4isAgreeCreditChangeDefault]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4timeLoan, .post, params: para), false) { model in
            self.loading.M4AlertViewHidden()
            if model.code == 1 {
                let data = model.data as? [String : Any]
                if type == 1 { //倒计时
                    let orderTime = data?["vcxvE"] as? Int ?? 0
                    self.M4TimerUI(time: orderTime)
                }
                else if type == 2 {//双授信
                    self.M4AgreeCreditChange()
                }
                else {//银行卡
                    self.M4ChangeBankInfo()
                }
            }
            else {
                self.view.makeToast(model.message, position: .center)
            }
        }
    }
    
}
